package com.hankol.community.viewmodel

import android.annotation.SuppressLint
import android.app.Activity
import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.util.DisplayMetrics
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.LinearLayout
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.MutableLiveData
import com.baselibrary.*
import com.baselibrary.base.mvvm.BaseViewModel
import com.baselibrary.bean.*
import com.baselibrary.extension.checkNotNull
import com.baselibrary.manager.DialogManager
import com.baselibrary.manager.LoadingManager
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.permission.PermissionCollection
import com.baselibrary.permission.PermissionsUtils
import com.baselibrary.permission.callback.PermissionsCall
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.view.ClickExpandListener
import com.baselibrary.view.share.SharePopupWindow
import com.baselibrary.activity.BaseActivity
import com.baselibrary.utils.ShareManager
import com.hankol.community.R
import com.hankol.community.SelectFriendShareActivity
import com.hankol.community.ShareFriendActivity
import com.hankol.community.api.CommunityConstant
import com.hankol.community.arouter.CommunityHelp
import com.hankol.community.bean.clientTimeline2SelectSendFriend2Bean
import com.hankol.community.databinding.FragmentVideoPageBinding
import com.hankol.community.databinding.PopupCommentlistBinding
import com.hankol.community.fragment.CommunityHomeFragment
import com.hankol.community.fragment.CommunityVideoFragment
import com.hankol.community.fragment.VideoPageFragment
import com.hankol.community.respository.CommunityRequestManager
import com.liaoinstan.springview.utils.DensityUtil
import com.media.publish.upload.impl.TVCUtils
import com.okhttp.SendRequest
import com.okhttp.callbacks.StringCallback
import com.okhttp.comment.CommentBean
import com.okhttp.comment.CommentReplyBean
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import com.tencent.rtmp.ITXVodPlayListener
import com.tencent.rtmp.TXLiveConstants
import com.tencent.rtmp.TXVodPlayer
import okhttp3.Request
import org.json.JSONException
import kotlin.math.roundToLong


/**
 * 首页 - 视频页
 * @Des：
 */
class VideoPageViewModel : BaseViewModel() {
    var commentListLiveData: MutableLiveData<CommentBean.DataBean> = MutableLiveData()
    var videoDetailsLD: MutableLiveData<VideoReadBean.DataBeanX> = MutableLiveData()
    var dynamicVideoLiveData: MutableLiveData<TimelineInfoData.ClientTimeline> = MutableLiveData()
    var historyAddLD: MutableLiveData<Any> = MutableLiveData()
    val UP_PLAYER = 200

    private var videoProgress: Long = 0
    private var videoDuration: Long = 0

    //视频页 列表
    fun reqVideoPageList(context: Context, cursor: String) {
        TVCUtils.getDevUUID(context)?.let {
            CommunityRequestManager.getInstance().reqVideoPageList(videoDetailsLD, cursor)
        }
    }
    //标记推荐视频已读
    fun reqVideoHistoryAdd(busiId: Long) {
        CommunityRequestManager.getInstance().reqVideoHistoryAdd(historyAddLD, busiId)
    }
    fun reqDynamicVideoDetails(dynamicId: Long) {
        CommunityRequestManager.getInstance().reqDynamicDetails(dynamicVideoLiveData, dynamicId)
    }

    fun reqCommentList(page: Int, typeId: Long, topCommentId: Long) {
        CommunityRequestManager.getInstance().reqCommentList(commentListLiveData, page, CommentEnum.COMMENT_DYNAMIC.commentType, typeId, 0, topCommentId)
    }

    fun openCommentViewOut(f: VideoPageFragment, viewListener: View.OnClickListener): PopupCommentlistBinding {
        val mPopupBinding = DataBindingUtil.bind<PopupCommentlistBinding>(LayoutInflater.from(f.context).inflate(R.layout.popup_commentlist, null))
        mPopupBinding!!.llVideoCommentHead.visibility = View.VISIBLE
        mPopupBinding.llPopupContent.setOnClickListener(f)
        mPopupBinding.tvPopupContent.setOnClickListener(f)
        mPopupBinding.tvPopupSend.setOnClickListener(f)
        f.activity?.let { openComment(it, mPopupBinding, f) }
        mPopupBinding.BaseCommentView.setEmptyViewListener(viewListener)
        return mPopupBinding
    }

    fun getStrAt(atMembers: List<TimelineInfoData.AtMembersBean>?): String? {
        return if (atMembers.checkNotNull()) {
            val mBuffer = StringBuffer()
            if (atMembers != null) {
                for (atMember in atMembers) {
                    mBuffer.append("@" + atMember.name).append("  ")
                }
            }
            mBuffer.toString()
        } else {
            ""
        }
    }


    @SuppressLint("SetTextI18n")
    fun setViewOut(mBinding: FragmentVideoPageBinding, it: TimelineInfoData.ClientTimeline, tHandler: Handler, mVodPlayer: TXVodPlayer, activity: Activity,fragment: VideoPageFragment) {
        mBinding.ivDetailsHead.setData(it.user.icon, it.user.isFans == 1)
        mBinding.ivDetailsFollow.visibility = when (it.user.id) {
            SpUtils.getInstance().userId -> View.GONE
            else -> View.VISIBLE
        }
        mBinding.tvDetailsName.paint.isFakeBoldText = true
        mBinding.ivDetailsFollow.isSelected = it.user.isFocusFans
        mBinding.tvDetailsName.text = "@${SpanUtils.appendEllipsis(it.user.name, 9)}"
        if (it.content.checkNotNull()) {
            mBinding.tvDetailsDes.visibility = View.VISIBLE
            mBinding.tvDetailsDes.setText(it.content)
            mBinding.tvDetailsDes.setListener(object : ClickExpandListener {
                override fun click() {
                    mBinding.svContent.visibility = View.VISIBLE
                    mBinding.tvDetailsDesExpand.text = it.content
                    mBinding.tvDetailsDes.visibility = View.GONE
                }
            })
            mBinding.tvDetailsCollapse.setOnClickListener {
                mBinding.tvDetailsDes.visibility = View.VISIBLE
                mBinding.tvDetailsDes.toggleCollapsed()
                mBinding.svContent.visibility = View.GONE
            }

        } else {
            mBinding.tvDetailsDes.visibility = View.GONE
        }
        cutHeight(activity)
        mBinding.ivDetailsGive.isLiked = it.isSupported
        mBinding.ivDetailsCollection.isLiked = it.isFavorited
        mBinding.ivDetailsInterval.text = TimeUtil.fromToday(it.ctime)
        mBinding.tvDetailsLocation.text = if (!CommonUtil.isBlank(it.address)) it.address else ""
        mBinding.tvDetailsShare.text = NumberUtils.formatBigNum((it.forwardNum + it.outForwardNum).toString())
        mBinding.tvDetailsGive.text = if (it.supportNum > 0) NumberUtils.formatBigNum(it.supportNum.toString()) else "赞"
        mBinding.tvDetailsLike.text = if (it.favoriteNum > 0) NumberUtils.formatBigNum(it.favoriteNum.toString()) else "收藏"
        mBinding.tvDetailsCommentNum.text = if (it.commentNum > 0) NumberUtils.formatBigNum(it.commentNum.toString()) else "抢首评"

        mBinding.llDetailsLocation.visibility = if (it.address.isBlank()) View.GONE else View.VISIBLE
        if (it.tags.isNotEmpty()) {
            mBinding.tvDetailsTopic.text = "#${it.tags[0]}"
            mBinding.tvDetailsTopic.visibility = View.VISIBLE
        } else {
            mBinding.tvDetailsTopic.visibility = View.GONE
        }
        if (it.showType == 4) { //转发的视频
            mBinding.tvDetailsName.text = "@${it.user.name}"
        }
        val url = if (it.showType == 2) it.video else it.forwardTimeline.video
        initPlayerViewOut(activity, url, tHandler, mVodPlayer, mBinding,fragment)
    }


    fun isAppInForeground(context: Context): Boolean {
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val appProcesses = activityManager.runningAppProcesses ?: return false
        for (appProcess in appProcesses) {
            if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName == context.packageName) {
                return true
            }
        }
        return false
    }
    private fun initPlayerViewOut(context: Context, url: String, tHandler: Handler, mVodPlayer: TXVodPlayer, mBinding: FragmentVideoPageBinding,fragment: VideoPageFragment) {
        if (TextUtils.isEmpty(url)) {
            ToastUtils.showShort(context, "视频链接出错")
            return
        }
        mBinding.tvvDetailsView.setLogMargin(12f, 12f, 110f, 60f)
        mBinding.tvvDetailsView.showLog(false)
        mBinding.tvvDetailsView.keepScreenOn = true
        mVodPlayer.setVodListener(object : ITXVodPlayListener {
            override fun onPlayEvent(txVodPlayer: TXVodPlayer, event: Int, param: Bundle) {
                when (event) {
                    TXLiveConstants.PLAY_EVT_VOD_PLAY_PREPARED -> {
                        mBinding.llTools.visibility=View.VISIBLE
                        if(isAppInForeground(context)&&fragment.isCurrentShow&&fragment.currentVideoId.equals("${fragment.mVideoId}")){//APP在前台时播放
                            mVodPlayer.resume()
                        }else{
                            if(fragment.currentVideoId.checkNotNull()) {
                                mVodPlayer.pause()
                            }else{//点击底部tab的刷新时，要继续播放
                                if(CommunityHomeFragment.currTab==2) {
                                    mVodPlayer.resume()
                                }else{
                                    mVodPlayer.pause()
                                }
                            }
                        }
                        mBinding.pbLoading.visibility = View.GONE
                        mBinding.ivDetailsPlay.isSelected = true
                    }
                    TXLiveConstants.PLAY_EVT_RCV_FIRST_I_FRAME -> {
                    }
                    TXLiveConstants.PLAY_EVT_PLAY_END -> {
                        mVodPlayer.seek(0)
                        mVodPlayer.resume()
                    }
                    TXLiveConstants.PLAY_EVT_PLAY_PROGRESS -> {
                        val progress = param.getInt(TXLiveConstants.EVT_PLAY_PROGRESS_MS)
                        val duration = param.getInt(TXLiveConstants.EVT_PLAY_DURATION_MS)
                        mBinding.sbDetailsDpeed.progress = progress
                        mBinding.sbDetailsDpeed.max = duration
                        videoProgress = progress.toLong()
                        videoDuration = duration.toLong()
                    }
                    else -> {
                    }
                }
                if (event < 0) // 播放点播文件失败
                    mVodPlayer.stopPlay(true)
            }

            override fun onNetStatus(txVodPlayer: TXVodPlayer, bundle: Bundle) {}
        })
        mVodPlayer.setPlayerView(mBinding.tvvDetailsView)
//        mVodPlayer.setAutoPlay(true)
        mVodPlayer.enableHardwareDecode(false) // 是否使用硬解码
        mVodPlayer.setRenderRotation(TXLiveConstants.RENDER_ROTATION_PORTRAIT) // player 渲染角度
        mVodPlayer.setRenderMode(TXLiveConstants.RENDER_MODE_ADJUST_RESOLUTION)
        val result: Int = mVodPlayer.startVodPlay(url)
        if (result == 0) {
            mBinding.ivDetailsPlay.isSelected = true
            hidePlayerView(tHandler)
        }
        mBinding.ivDetailsPlay.setOnClickListener { v: View? ->
            hidePlayerView(tHandler)
            if (mVodPlayer.isPlaying) {
                mVodPlayer.pause()
                mBinding.ivDetailsPlay.isSelected = false
            } else {
                mVodPlayer.resume()
                mBinding.ivDetailsPlay.isSelected = true
            }
        }
    }

    fun setNameTVMaxWidthOut(activity: Activity, mBinding: FragmentVideoPageBinding): Int {
        val marginSum = ScreenUtils.marginSum(activity, 14, 12, 11, 16)
        return ScreenUtils.getUserNameMaxWidth(activity, marginSum, mBinding.llTools, mBinding.ivDetailsInterval)
    }

    fun hidePlayerView(tHandler: Handler) {
        tHandler.removeMessages(UP_PLAYER)
        tHandler.sendEmptyMessageDelayed(UP_PLAYER, 3000)
    }

    fun addComment(type: Int, typeId: Int, edContent: TextView, activity: Activity, listener: OnPublishCompleteListener?) {
        val content = edContent.text.toString().trim()
        if (CommonUtil.isBlank(content)) {
            ToastUtils.showShort(activity, "请输入")
            return
        }

        SendRequest.commentAdd(SpUtils.getInstance().userToken, SpUtils.getInstance().userId, type, typeId, content, object : StringCallback() {
            override fun onBefore(request: Request, id: Int) {
                super.onBefore(request, id)
                LoadingManager.showLoadingDialog(activity, null)
            }

            override fun onAfter(id: Int) {
                super.onAfter(id)
                LoadingManager.hideLoadingDialog(activity)
            }

            override fun onError(call: okhttp3.Call, e: Exception, id: Int) {}
            override fun onResponse(response: String, id: Int) {
                try {
                    val mCommentReplyBean = GsonUtils.parseJsonToBean(response, CommentReplyBean::class.java)
                    if (mCommentReplyBean != null && mCommentReplyBean.isSuccess) {
                        edContent.text = ""
                        if (mCommentReplyBean.data.getRewardScore() > 0) {
                            //发表评论
                            DialogManager.showCoinDialog(activity, "评论成功", mCommentReplyBean.data.getRewardScore())
                            reqUpUserInfo()
                        }

                        listener?.onPublishComplete(mCommentReplyBean)
                        KeyBoardUtils.hideShowKeyboard(activity)
                    } else {
                        ToastUtils.showShort(activity, mCommentReplyBean.msg)
                    }
                } catch (e: JSONException) {
                    e.printStackTrace()
                }
            }
        })
    }

    /**
     * 更新收藏状态
     */
    fun upCollectionStateOut(data: TimelineInfoData.ClientTimeline?, mBinding: FragmentVideoPageBinding) {
        data?.apply {
            mBinding.ivDetailsCollection.isEnabled = true
            favoriteNum = if (isFavorited) {
                //说明是取消点赞
                ToastUtils.showShort(ContextUtils.getCurApplication().applicationContext, "取消收藏")
                favoriteNum.minus(1)
            } else {
                //说明是进行点赞
                ToastUtils.showShort(ContextUtils.getCurApplication().applicationContext, "收藏成功")
                favoriteNum.plus(1)
            }
            isFavorited = !isFavorited
            mBinding.ivDetailsCollection.isLiked = isFavorited

            mBinding.tvDetailsLike.text = if (favoriteNum > 0) NumberUtils.formatBigNum(favoriteNum.toString()) else "收藏"
            if (favoriteNum < 0) favoriteNum = 0//避免出现负数

            EventBusUtils.sendNotify1Value(MessageBus.msgId_change_dynamic_collect_status, data.id.toInt())
        }
    }


    /**
     * 更新点赞状态
     */
    fun upSupportedStateOut(data: TimelineInfoData.ClientTimeline?, mBinding: FragmentVideoPageBinding): Boolean {
        data?.apply {
            mBinding.ivDetailsGive.isEnabled = true
            supportNum = if (isSupported) {
                //原始值是true 则表示是取消操作
                supportNum.minus(1)
            } else {
                supportNum.plus(1)
            }
            isSupported = !isSupported
            mBinding.ivDetailsGive.isLiked = isSupported
            mBinding.tvDetailsGive.text = if (supportNum > 0) NumberUtils.formatBigNum(supportNum.toString()) else "收藏"
            if (supportNum < 0) supportNum = 0//避免出现负数

            EventBusUtils.sendNotify1Value(MessageBus.msgId_change_dynamic_like_status, data.id.toInt())
            return isSupported
        }
        return false

    }

    fun openComment(activity: Activity, mPopupBinding: PopupCommentlistBinding, listener: OnRefreshLoadMoreListener) {
        //弹窗Popup
        val mSpringPopup: SmartRefreshLayout = mPopupBinding.smartComment

        val linearParams = mPopupBinding.BaseCommentView.layoutParams as LinearLayout.LayoutParams
        linearParams.height = cutHeight(activity)
        mPopupBinding.BaseCommentView.layoutParams = linearParams
        mPopupBinding.BaseCommentView.setEmptyImgSize(DensityUtil.dip2px(activity, 200f), DensityUtil.dip2px(activity, 200f))
        mSpringPopup.setOnRefreshLoadMoreListener(listener)
        mPopupBinding.BaseCommentView.setAdapter(activity, null)

        mPopupBinding.BaseCommentView.visibility = View.GONE
        mPopupBinding.PBarSldComment.visibility = View.VISIBLE

    }


    fun share(data: TimelineInfoData.ClientTimeline, activity: BaseActivity, communityHelp: CommunityHelp): SharePopupWindow? {
        var mVideoUrl = ""
        val shareUrl = Constants.DYNAMIC_SHARE_URL + data.id
        if (data.showType == 2) { //视频
            mVideoUrl = data.video
        } else if (data.showType == 4) { //转发的视频
            if (data.forwardTimeline != null) {
                if (data.forwardTimeline.showType == 2) {
                    mVideoUrl = data.forwardTimeline.video
                }
            }
        }
        val title = if (data.content.checkNotNull()) data.content else "@${data.user.name}发了一个视频，快点开来看看！"
        val des = if (data.content.checkNotNull()) data.content else " "
        var showShare = ShareManager.showSharePopWindow(activity, shareUrl, data.cover, title, des, object : SharePopupWindow.OnShareClickListener {
            override fun onShareClick(type: Int) {
                when (type) {

                    ShareItemBean.WXZone, ShareItemBean.WX -> {
                        reqAddShareNum(data.id)
                    }

                    ShareItemBean.DOWN -> {
                        PermissionsUtils.getInstance().chekPermissions(activity, PermissionCollection.FILE.permissionList, object : PermissionsCall() {
                            override fun permissionsPass() {
                                VideoDownloadUtil.download(activity, mVideoUrl, ".mp4")
                            }
                        })
                    }
                    ShareItemBean.POSTER -> {
                        PermissionsUtils.getInstance().chekPermissions(activity, PermissionCollection.FILE.permissionList, object : PermissionsCall() {
                            override fun permissionsPass() {
                                LoadingManager.showLoadingDialog(activity)
                                var sharePosterBean: SharePosterBean = changePosterBean(data)
                                sharePosterBean.imagePaths = ArrayList()
                                for (i in 0..2) {
                                    val posterStyle = PosterStyle(activity, sharePosterBean, i) { path: String? ->
                                        sharePosterBean.imagePaths.add(path)
                                        checkListSize(activity, sharePosterBean)
                                    }
                                    posterStyle.startDraw()
                                }
                            }
                        })
                    }
                    ShareItemBean.REPORT -> {
                        val intent = Intent()
                        val bundle = Bundle()
                        bundle.putInt("type", 3)
                        bundle.putInt("id", data.id.toInt())
                        bundle.putInt("complaintUserId", data.user.id.toInt())
                        intent.putExtras(bundle)
                        activity.openActivity(communityHelp.getJuBaoOneActivity(), bundle)

                    }
                }
            }

            fun checkListSize(activity: Activity, sharePosterBean: SharePosterBean) {
                if (sharePosterBean.imagePaths.size == 3) {
                    LoadingManager.hideLoadingDialog(activity)
                    val bundle = Bundle()
                    bundle.putSerializable(Constants.SHARE_POSTER_BEAN, sharePosterBean)
                    ActivityRouter.startActivity(ActivityRouter.ACTIVITY.SHARE_POSTER_SELECT, bundle)
                }
            }

            override fun onShareFriendClick(bean: ShareItemBean) {
                if (bean.userId == 0L) {
                    val intent = Intent(activity, SelectFriendShareActivity::class.java)
                    intent.putExtra("friend", bean)
                    intent.putExtra("dynamic", clientTimeline2SelectSendFriend2Bean(data))
                    activity.startActivity(intent)
                } else {
                    val intent = Intent(activity, ShareFriendActivity::class.java)
                    intent.putExtra("friend", bean)
                    intent.putExtra("dynamic", clientTimeline2SelectSendFriend2Bean(data))
                    activity.startActivity(intent)
                }
            }

        })
        showShare?.setShareItem(true, false, true);
        return showShare
    }

    fun changePosterBean(data: TimelineInfoData.ClientTimeline): SharePosterBean {

        val sharePosterBean = SharePosterBean(2)
        sharePosterBean.userAvatar = data.user.icon
        sharePosterBean.userName = data.user.name
        sharePosterBean.shareImage = data.cover
        sharePosterBean.shareContent = data.content
        sharePosterBean.atPersonName = getStrAt(data.atMembers)
        sharePosterBean.isVideo = data.showType == 2
        sharePosterBean.isFans = data.user.isFans == 1
        sharePosterBean.isWinnery = data.user.isWinery != 0
        return sharePosterBean
    }


    fun cutHeight(context: Context): Int {
        val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val dm = DisplayMetrics()
        wm.defaultDisplay.getMetrics(dm)
        val mScreenHeight = dm.heightPixels // 屏幕高度（像素）z
        return mScreenHeight / 2
    }

    fun sensorsFollow(sponsorUser: UserInfo?, bean: TimelineInfoData.SimpleUser) {
        sponsorUser?.data?.let {
            SensorsDataManager.instance.attention(it.name, it.id.toString(), bean.name, bean.id.toString(), CommunityConstant.DYNAMIC_POINT, true)
        }
    }

    interface OnPublishCompleteListener {
        fun onPublishComplete(bean: CommentReplyBean)
    }
}
